import { getCode, login } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'

const user = {
  state: {
    token: getToken(),
    username: '',
    id: ''
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USERNAME: (state, username) => {
      state.username = username
    },
    SET_ID: (state, id) => {
      state.id = id
    }
  },

  actions: {
    Getcode({ commit }, phone) {
      return new Promise((resolve, reject) => {
        getCode(phone).then(response => {
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 登录
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(response => {
          const data = response.data
          if (response.code === 1) {
            setToken(data.token)
            commit('SET_TOKEN', data.token)
            commit('SET_USERNAME', data.username)
            commit('SET_ID', data.id)
            sessionStorage.setItem('token', data.token)
            sessionStorage.setItem('username', data.username)
            sessionStorage.setItem('id', data.id)
            sessionStorage.setItem('adminFlag', data.adminFlag)
            sessionStorage.setItem('pid', data.pid)
            resolve()
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    LogOut({ commit, state }) {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      sessionStorage.removeItem('token')
      sessionStorage.removeItem('id')
      sessionStorage.removeItem('username')
      sessionStorage.removeItem('adminFlag')
      removeToken()
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
